import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加token等
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 统一错误处理
    const message = error.response?.data?.message || error.message || '请求失败'
    console.error('API Error:', message)
    return Promise.reject(error)
  }
)

/**
 * 上传单张图片
 */
export const uploadImage = async (file) => {
  const formData = new FormData()
  formData.append('image', file)
  
  return api.post('/upload/image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 上传多张图片
 */
export const uploadImages = async (files) => {
  const formData = new FormData()
  files.forEach(file => {
    formData.append('images', file)
  })
  
  return api.post('/upload/images', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除图片
 */
export const deleteImage = async (dateDir, filename) => {
  return api.delete(`/upload/${dateDir}/${filename}`)
}

/**
 * 保存文章
 */
export const saveArticle = async (articleData) => {
  return api.post('/articles', articleData)
}

/**
 * 获取文章列表
 */
export const getArticles = async (params) => {
  return api.get('/articles', { params })
}

/**
 * 获取文章详情
 */
export const getArticle = async (id) => {
  return api.get(`/articles/${id}`)
}

/**
 * 更新文章
 */
export const updateArticle = async (id, articleData) => {
  return api.put(`/articles/${id}`, articleData)
}

/**
 * 删除文章
 */
export const deleteArticle = async (id) => {
  return api.delete(`/articles/${id}`)
}

/**
 * 获取模板列表
 */
export const getTemplates = async () => {
  return api.get('/templates')
}

/**
 * 保存导出记录
 */
export const saveExport = async (exportData) => {
  return api.post('/exports', exportData)
}

export default api

